package com.yeung.springcloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.yeung.springcloud.entities.Dept;
import com.yeung.springcloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
public class DeptController {
    @Autowired
    private DeptService service;
    @Autowired
    private DiscoveryClient client;//服务发现的客户端, 让别人发现我有哪些服务

    @RequestMapping(value = "/dept/add", method = RequestMethod.POST)
    public boolean add(@RequestBody Dept dept) {
        return service.add(dept);
    }

    /**
     * // Hystrix 有点像Aop的环绕通知的处理方式,拦截处理异常,执行指定的处理方法
     * 本方法,用了自定义类实现fallbackFactory类, 来统一处理当前service的所有方法的
     * 异常处理, 而不用针对每个方法添加熔断注解,并指定熔断处理的方法
     * 所以一下代码注释掉了
     * //    @HystrixCommand(fallbackMethod = "processHystrix_Get")
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
//    @HystrixCommand(fallbackMethod = "processHystrix_Get")
    public Dept get(@PathVariable("id") Long id) {
        Dept dpt = service.get(id);
        if (dpt == null) {
            //不存在该值, 或出现异常就会执行熔断的方法
            throw new RuntimeException("该ID: " + id + "没有对应的信息");
        }
        return dpt;
    }

    /**
     * 熔断处理方法
     * 针对get方法的熔断处理
     *
     * @param id
     * @return
     */
    public Dept processHystrix_Get(@PathVariable("id") Long id) {
        return new Dept().setDeptno(id).setDname("该ID" + id + "没有对应的信息").setDb_source("no this database in Mysql");
    }


    @RequestMapping(value = "/dept/list", method = RequestMethod.GET)
    @HystrixCommand(fallbackMethod = "processHystrix_List")
    public List<Dept> list() {
        return service.list();
    }

    public List<Dept> processHystrix_List() {
        return new ArrayList<>();
    }

    @RequestMapping(value = "/dept/discovery", method = RequestMethod.GET)
    public Object discovery() {
        List<String> list = client.getServices();//盘点微服务应用有哪些
        System.out.println("*****" + list);

        List<ServiceInstance> srvList = client.getInstances("MICROSERVICECLOUD-DEPT");//微服务的名称获取服务应用实例
        for (ServiceInstance ele : srvList) {
            System.out.println(ele.getServiceId() + "\t" + ele.getHost() + "\t" + ele.getPort() + "\t" + ele.getUri());
        }
        return this.client;
    }


}
